/*
 * @Author: xiaosihan
 * @Date: 2024-07-15 23:14:14
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-09-20 07:40:52
 */

// 用户相关的数据
import { default as loginApi, default as loginAPI } from "@api/loginAPI";
import hashHistory from "@hashHistory";
import { UserData } from "@type";
import { get, isUndefined } from "lodash";
import { configure, observable } from "mobx";

configure({ enforceActions: "never" });

const userStore = (window.userStore = observable({
  //用户id
  userId: "",
  // 用户名
  name: "用户名",
  //手机号码
  phone: "",
  //头像
  avatarUrl: "",
  //是否登录 undefined 为等待登录
  isLogin: undefined as boolean | undefined,
  //等待登录
  async awaitLogin() {
    while (!this.isLogin) {
      await new Promise((resolve) => setTimeout(resolve, 200));
    }
  },
  //等待登录状态
  async awaitLoginState() {
    while (isUndefined(this.isLogin)) {
      await new Promise((resolve) => setTimeout(resolve, 200));
    }
  },
  // 获取用户信息
  async getUserInfo() {
    if (localStorage.token) {
      const result = await loginAPI.get_user_info();
      const name = get(result, ["data", "data", "name"]);
      const Phone = get(result, ["data", "data", "phone"]);
      const id = get(result, ["data", "data", "id"]);
      const avatarUrl = get(result, ["data", "data", "avatarUrl"]);
      const success = get(result, ["data", "success"]);

      if (success) {
        this.userId = id;
        this.name = name;
        this.phone = Phone;
        this.avatarUrl = avatarUrl;
        this.isLogin = true;
      } else {
        this.isLogin = false;
        if (
          !(
            location.hash.includes("admin") ||
            location.hash.includes("factory")
          )
        ) {
          hashHistory.push("/");
        }
      }
    } else {
      this.isLogin = false;
      if (
        !(
          location.hash.includes("admin") ||
          location.hash.includes("factory")
        )
      ) {
        hashHistory.push("/");
      }
    }
  },

  //验证码登录
  async loginByPhone(phone: string, code: string) {
    const result = await loginApi.sms_login(phone, code);
    const name = get(result, ["data", "name"]);
    const id = get(result, ["data", "id"]);
    const Phone = get(result, ["data", "phone"]);
    const token = get(result, ["data", "token"]);
    const success = get(result, ["success"]);
    const message = get(result, ["message"]);
    if (success) {
      localStorage.token = token;
      this.userId = id;
      this.name = name;
      this.phone = Phone;
      this.isLogin = true;
      return "";
    } else {
      this.isLogin = false;
      return message;
    }
  },

  //修改用户信息
  async updateUser(userData: Partial<UserData>) {
    const res = await loginAPI.updateUser({ ...userData, id: this.userId });
    this.getUserInfo();
    return res;
  },
  //验证原手机
  async checkPhone(phone: string, code: string) {
    const res = await loginAPI.checkPhone({ phone, code });
    const success = get(res, ["success"]);
    const message = get(res, ["message"]);
    if (success) {
      this.getUserInfo();
      return "";
    } else {
      return message;
    }
  },
  //修改手机号
  async updatePhone(phone: string, code: string) {
    const res = await loginAPI.updatePhone({ phone, code });
    this.getUserInfo();
    const success = get(res, ["success"]);
    const message = get(res, ["message"]);
    if (success) {
      this.getUserInfo();
      return "";
    } else {
      return message;
    }
  },
  //退出登录
  loginOut() {
    localStorage.token = "";
    this.isLogin = false;
    hashHistory.push("/");
    this.name = "";
    this.phone = "";
  },
}));

userStore.getUserInfo();

export default userStore;
